// API客户端模块 - 替代localStorage操作
const ApiClient = (() => {
  const BASE_URL = window.location.origin;
  
  /**
   * 通用API请求方法
   * @param {string} url - 请求的URL路径
   * @param {Object} options - 请求选项配置
   * @returns {Promise<Object>} 返回解析后的JSON响应数据
   */
  const request = async (url, options = {}) => {
    try {
      const response = await fetch(`${BASE_URL}${url}`, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers
        },
        ...options
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || `HTTP ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      // console.error('API request failed:', error);
      throw error;
    }
  };
  
  /**
   * 获取用户个人单词库
   * @returns {Promise<Object>} 返回包含单词数组和统计信息的对象
   */
  const getAllWords = async () => {
    // 获取当前登录用户ID
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    const response = await request(`/api/words?userId=${user.id}`);
    const words = response.words || [];
    
    // 如果用户词库为空，自动初始化
    if (words.length === 0) {
      // console.log('🔄 用户词库为空，正在初始化...');
      try {
        await initializeUserVocabulary();
        // 重新获取初始化后的数据
        const newResponse = await request(`/api/words?userId=${user.id}`);
        return newResponse.words || [];
      } catch (error) {
        // console.error('初始化用户词库失败:', error);
        return words; // 返回空数组
      }
    }
    
    return words;
  };
  
  /**
   * 初始化用户个人词库
   * @returns {Promise<Object>} 返回初始化结果
   */
  const initializeUserVocabulary = async () => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request('/api/users/initialize-vocabulary', {
      method: 'POST',
      body: JSON.stringify({
        userId: user.id
      })
    });
  };
  
  /**
   * 获取当前用户信息
   * @returns {Object|null} 返回用户信息或null
   */
  const getCurrentUser = () => {
    try {
      // 优先从localStorage获取用户信息
      let userStr = localStorage.getItem('user');
      
      // 如果localStorage中没有，从sessionStorage获取
      if (!userStr) {
        userStr = sessionStorage.getItem('user');
      }
      
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      // console.error('Failed to parse user data:', error);
      return null;
    }
  };
  
  /**
   * 添加新单词到用户个人单词库
   * @param {Object} wordData - 单词数据对象
   * @param {string} wordData.word - 单词
   * @param {string} wordData.pronunciation - 发音
   * @param {string} wordData.translation - 翻译
   * @param {string} wordData.example - 例句
   * @returns {Promise<Object>} 返回添加的单词对象
   */
  const addWord = async (wordData) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request('/api/words', {
      method: 'POST',
      body: JSON.stringify({
        ...wordData,
        userId: user.id
      })
    });
  };
  
  /**
   * 更新用户个人单词库中的单词
   * @param {string} id - 单词ID
   * @param {Object} wordData - 更新的单词数据
   * @returns {Promise<Object>} 返回更新后的单词对象
   */
  const updateWord = async (id, wordData) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request(`/api/words/${id}`, {
      method: 'PUT',
      body: JSON.stringify({
        ...wordData,
        userId: user.id
      })
    });
  };
  
  /**
   * 从用户个人单词库中删除单词
   * @param {string} id - 单词ID
   * @returns {Promise<Object>} 返回删除结果
   */
  const deleteWord = async (id) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request(`/api/words/${id}?userId=${user.id}`, {
      method: 'DELETE'
    });
  };
  
  /**
   * 切换用户个人单词库中单词的记忆状态
   * @param {string} id - 单词ID
   * @returns {Promise<Object>} 返回更新后的单词对象
   */
  const toggleMemorized = async (id) => {
    const user = getCurrentUser();
    if (!user || !user.id) {
      throw new Error('用户未登录或用户信息无效');
    }
    
    return await request(`/api/words/${id}/memorized`, {
      method: 'PATCH',
      body: JSON.stringify({
        userId: user.id
      })
    });
  };
  
  /**
   * 搜索单词
   * @param {string} query - 搜索关键词
   * @returns {Promise<Array>} 返回匹配的单词数组
   */
  const searchWords = async (query) => {
    const params = query ? `?q=${encodeURIComponent(query)}` : '';
    return await request(`/api/words/search${params}`);
  };
  
  /**
   * 获取基础词库数据（供未登录用户使用）
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} search - 搜索关键词
   * @returns {Promise<Array>} 返回基础词库数组
   */
  const getBaseVocabulary = async (page = 1, limit = 1000, search = '') => {
    const params = new URLSearchParams({
      page: page.toString(),
      limit: limit.toString(),
      search
    });
    
    const response = await request(`/api/base-vocabulary?${params}`);
    return response.words || [];
  };
  
  /**
   * 更新用户信息
   * @param {string} userId - 用户ID
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} 返回更新结果
   */
  const updateUserInfo = async (userId, userData) => {
    return await request(`/api/users/${userId}`, {
      method: 'PUT',
      body: JSON.stringify(userData)
    });
  };

  return {
    getAllWords,
    addWord,
    updateWord,
    deleteWord,
    toggleMemorized,
    searchWords,
    getBaseVocabulary,
    initializeUserVocabulary,
    updateUserInfo
  };
})();

// 兼容原有的WordData接口
const WordData = (() => {
  // 数据缓存
  let wordsCache = null;
  let isDataLoaded = false;
  
  /**
   * 初始化数据，从服务器加载用户个人单词数据
   * @returns {Promise<Array>} 返回单词数据数组
   */
  const initializeData = async () => {
    if (isDataLoaded && wordsCache) return wordsCache;
    
    // 检查用户登录状态
    const user = getCurrentUser();
    if (!user || !user.id) {
      // console.log('用户未登录，加载基础词库数据');
      try {
        wordsCache = await ApiClient.getBaseVocabulary();
      } catch (error) {
        // console.error('Failed to load base vocabulary:', error);
        wordsCache = [];
      }
      isDataLoaded = true;
      return wordsCache;
    }
    
    try {
      wordsCache = await ApiClient.getAllWords();
      isDataLoaded = true;
      return wordsCache;
    } catch (error) {
      // console.error('Failed to initialize data:', error);
      wordsCache = [];
      isDataLoaded = true;
      return wordsCache;
    }
  };
  
  /**
   * 获取当前用户信息
   * @returns {Object|null} 返回用户信息或null
   */
  const getCurrentUser = () => {
    try {
      // 优先从localStorage获取用户信息
      let userStr = localStorage.getItem('user');
      
      // 如果localStorage中没有，从sessionStorage获取
      if (!userStr) {
        userStr = sessionStorage.getItem('user');
      }
      
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      // console.error('Failed to parse user data:', error);
      return null;
    }
  };
  
  /**
   * 获取所有单词（同步版本，使用缓存）
   * @returns {Array} 返回缓存中的单词数组
   */
  const getAllWords = () => {
    return wordsCache || [];
  };
  
  /**
   * 获取所有单词（异步版本）
   * @returns {Promise<Array>} 返回单词数据数组
   */
  const getAllWordsAsync = async () => {
    if (!isDataLoaded) {
      await initializeData();
    }
    return wordsCache || [];
  };
  
  /**
   * 刷新缓存数据
   * @returns {Promise<Array>} 返回刷新后的单词数组
   */
  const refreshCache = async () => {
    // 检查用户登录状态
    const user = getCurrentUser();
    if (!user || !user.id) {
      // console.log('用户未登录，加载基础词库数据');
      try {
        wordsCache = await ApiClient.getBaseVocabulary();
      } catch (error) {
        // console.error('Failed to load base vocabulary:', error);
        wordsCache = [];
      }
      return wordsCache;
    }
    
    try {
      wordsCache = await ApiClient.getAllWords();
      return wordsCache;
    } catch (error) {
      // console.error('Failed to refresh cache:', error);
      return wordsCache || [];
    }
  };
  
  /**
   * 添加新单词
   * @param {Object} wordData - 单词数据对象
   * @param {string} wordData.word - 单词
   * @param {string} wordData.pronunciation - 发音
   * @param {string} wordData.translation - 翻译
   * @param {string} wordData.example - 例句
   * @returns {Promise<Object>} 返回新创建的单词对象
   */
  const addWord = async (wordData) => {
    try {
      const newWord = await ApiClient.addWord(wordData);
      // 更新缓存
      if (wordsCache) {
        wordsCache.unshift(newWord);
      }
      return newWord;
    } catch (error) {
      // console.error('Failed to add word:', error);
      throw error;
    }
  };
  
  /**
   * 更新单词
   * @param {string} id - 单词ID
   * @param {Object} wordData - 更新的单词数据对象
   * @returns {Promise<Object>} 返回更新后的单词对象
   */
  const updateWord = async (id, wordData) => {
    try {
      const updatedWord = await ApiClient.updateWord(id, wordData);
      // 更新缓存
      if (wordsCache) {
        const index = wordsCache.findIndex(word => word.id === id);
        if (index !== -1) {
          wordsCache[index] = updatedWord;
        }
      }
      return updatedWord;
    } catch (error) {
      // console.error('Failed to update word:', error);
      throw error;
    }
  };
  
  /**
   * 删除单词
   * @param {string} id - 要删除的单词ID
   * @returns {Promise<boolean>} 返回删除操作是否成功
   */
  const deleteWord = async (id) => {
    try {
      await ApiClient.deleteWord(id);
      // 更新缓存
      if (wordsCache) {
        const index = wordsCache.findIndex(word => word.id === id);
        if (index !== -1) {
          wordsCache.splice(index, 1);
        }
      }
      return true;
    } catch (error) {
      // console.error('Failed to delete word:', error);
      throw error;
    }
  };
  
  /**
   * 切换单词记忆状态
   * @param {string} id - 单词ID
   * @returns {Promise<Object>} 返回更新后的单词对象
   */
  const toggleMemorized = async (id) => {
    try {
      const updatedWord = await ApiClient.toggleMemorized(id);
      // 更新缓存
      if (wordsCache) {
        const index = wordsCache.findIndex(word => word.id === id);
        if (index !== -1) {
          wordsCache[index] = updatedWord;
        }
      }
      return updatedWord;
    } catch (error) {
      // console.error('Failed to toggle memorized status:', error);
      throw error;
    }
  };
  
  /**
   * 搜索单词
   * @param {string} query - 搜索关键词
   * @returns {Promise<Array>} 返回匹配的单词数组
   */
  const searchWords = async (query) => {
    try {
      return await ApiClient.searchWords(query);
    } catch (error) {
      // console.error('Failed to search words:', error);
      // 降级到本地搜索
      if (!query) return getAllWords();
      
      const words = getAllWords();
      const lowerQuery = query.toLowerCase();
      return words.filter(word => 
        word.word.toLowerCase().includes(lowerQuery) || 
        word.translation.toLowerCase().includes(lowerQuery)
      );
    }
  };
  
  return {
    getAllWords,
    getAllWordsAsync,
    initializeData,
    refreshCache,
    addWord,
    updateWord,
    deleteWord,
    toggleMemorized,
    searchWords
  };
})();